#ifndef __THREAD_HPP__
#define __THREAD_HPP__

#include <iostream>
#include <functional>
#include <pthread.h>
#include <string>
#include <cstdint>

namespace ThreadModule
{
    static uint32_t number = 1;

    class Thread
    {
        using func_t = std::function<void()>;

    private:
        void EnableDetach()
        {
            _isdetach = true;
        }

        void EnableRunning()
        {
            _isrunning = true;
        }

        static void *Routine(void *arg)
        {
            Thread *self = static_cast<Thread *>(arg);
            self->EnableRunning();
            if (self->_isdetach)
                self->Detach();
            pthread_setname_np(self->_tid, self->_name.c_str());
            self->_func();
            return nullptr;
        }

    public:
        Thread(func_t func)
            : _func(func), _tid(0), _isrunning(false), _isdetach(false), res(nullptr)
        {
            _name = "thread-" + std::to_string(number++);
        }

        void Detach()
        {
            if (_isdetach)
                return;
            if (_isrunning)
            {
                pthread_detach(_tid);
            }
            EnableDetach();
        }

        bool Start()
        {
            if (_isrunning)
                return false;
            int n = pthread_create(&_tid, nullptr, Routine, this);
            if (n != 0)
                return false;
            else
                return true;
        }

        bool Stop()
        {
            if (_isrunning)
            {
                int n = pthread_cancel(_tid);
                if (n != 0)
                    return false;
                else
                {
                    _isrunning = false;
                    return true;
                }
            }
            return false;
        }

        void Join()
        {
            if (_isdetach)
                return;
            if (_isrunning)
            {
                int n = pthread_join(_tid, &res);
                (void)n;
            }
        }

        pthread_t Id(){
            return _tid;
        }
        
        ~Thread()
        {
        }

    private:
        func_t _func;
        std::string _name;
        bool _isrunning;
        bool _isdetach;
        void *res;
        pthread_t _tid;
    };

}

#endif